﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Helpers;
using System.Xml;

namespace LifeFlow.Servicer
{
    internal class InternalKeyHandler : IKeyHandler
    {
        public InternalKeyHandler()
        {
            LoadList();
        }

        private static List<ApiConsumer> _consumers;

        public void AddToList(object consumer)
        {
            _consumers.Add((ApiConsumer)consumer);

            var sw = new StreamWriter("apiconsumer.list", false);
            sw.Write(Json.Encode(_consumers));
            sw.Flush();
            sw.Close();
        }

        public bool IsValid(string token)
        {
            var g = Guid.Empty;
            Guid.TryParse(token, out g);
            return _consumers.Any(c => c.Key == g);
        }

        internal void LoadList()
        {
            var result = new List<ApiConsumer>();

            if (File.Exists("apiconsumer.list"))
            {
                var sr = new StreamReader("apiconsumer.list");
                string r = sr.ReadToEnd();
                sr.Close();

                result = Json.Decode<List<ApiConsumer>>(r);
            }

            _consumers = result;
        }
    }

    public class ApiConsumer
    {
        public Guid Key { get; set; }
        public string Name { get; set; }
    }
}
